#include <list>
#include <ctime>
#include <cstdlib>

#include "food_define.h"
#include "snake_define.h"

extern std::list<FoodNode> food_list;
extern std::list<Snake> snake_list;

int seed  = time(NULL);


/*
*@func:获取一个范围在[0, n-1]之间的随机数
*/
int get_my_rand(int floor)
{
    //srand(unsigned(time(NULL)));//不可行，可能是因为计算机太快，重复生成时，time(NULL)几乎不变
    srand(seed);
    seed +=10;
    return rand()%floor;
}


/*
*@func:检查当前生成的食物，是否与已经有的食物、蛇身坐标相互冲突；如果有冲突，返回false,反之为true
*/
bool FoodNode::check_valid()
{
    //不能落在已有的食物上面
    if(!food_list.empty())
    {
        for(auto iter=food_list.begin();iter!=food_list.end(); iter++)
        {
            if(m_x == iter->get_x() && m_y == iter->get_y())
            {
                return false;
            }
        }
    }

    //不能落在蛇身上面
    if(!snake_list.empty())
    {
        for(auto siter=snake_list.begin(); siter!=snake_list.end(); siter++)
        {
            //对单条蛇的每一节蛇身进行检查

            for(auto biter= siter->get_snake_total().begin(); biter!=siter->get_snake_total().end(); biter++)
            {
                if((m_x == biter->x)&&(m_y == biter->y))
                {
                    return false;
                }
            }
        }
    }
    return true;
}


void FoodNode::create_a_valid_food()
{
    do
    {   
        set_rand_pos();
    } while (!check_valid());

    food_list.push_back(*this);

    //到此处自动销毁newNode
    printf("New food's pos[%d, %d]\n", m_x, m_y);
}